using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using S.M.SmartMedical.Infrastructure;
using S.M.SmartMedical.Infrastructure.BaseRepository;
using System.Reflection;

namespace S.M.SmartMedical.API.Read
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // 添加控制器服务
            builder.Services.AddControllers();
            builder.Services.AddEndpointsApiExplorer();

            // 添加Swagger文档支持
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title = "智慧医疗API - 查询服务",
                    Version = "v1",
                    Description = "智慧医疗系统查询接口文档"
                });

                // 设置XML注释文件路径
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                if (File.Exists(xmlPath))
                {
                    c.IncludeXmlComments(xmlPath);
                }
            });

            // 配置数据库连接
            builder.Services.AddDbContext<MyDbContext>(options =>
            {
                options.UseMySql(builder.Configuration.GetConnectionString("Conn"), new MySqlServerVersion("5.7"));
            });

            // 注册仓储服务
            builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
            builder.Services.AddScoped<DbContext>(provider => provider.GetRequiredService<MyDbContext>());

            // 注册MediatR
            builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

            // 注册AutoMapper
            builder.Services.AddAutoMapper(typeof(MapperProfiles));

            // 配置CORS
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", policy =>
                {
                    policy.AllowAnyOrigin()
                          .AllowAnyMethod()
                          .AllowAnyHeader();
                });
            });

            var app = builder.Build();

            // 配置HTTP请求管道

            // 开发环境启用Swagger
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            // 启用CORS
            app.UseCors("AllowAll");

            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}
